package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.DAO;
import model.UserProfile;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.*;

import com.google.appengine.api.urlfetch.*;

//import java.util.logging.Logger;

public class UserServlet extends HttpServlet{
	
	//private static final Logger log = Logger.getLogger(UserServlet.class.getName());
	private DAO dao = new DAO();
	ObjectMapper mapper = new ObjectMapper();
	
	private String getUserProfile(String id) throws JsonGenerationException, JsonMappingException, IOException
	{
		UserProfile user = dao.getUserProfileById(id);				
		return mapper.writeValueAsString(user);		
	}
	
	private String getUserName(String id) throws JsonGenerationException, JsonMappingException, IOException
	{

		UserProfile user = dao.getUserProfileById(id);				
		String username = user.getName();
				
		Map<String,String> nameStruct = new HashMap<String,String>();
		nameStruct.put("name", username);
	
		return mapper.writeValueAsString(nameStruct);		
	}
	
	private String getUserNameByFB(String fbid) throws JsonGenerationException, JsonMappingException, IOException
	{

		UserProfile user = dao.getUserProfileByFBId(fbid);
		String username;
		if(user != null)
			username = user.getName();
		else
			username = "NULL";
				
		Map<String,String> nameStruct = new HashMap<String,String>();
		nameStruct.put("name", username);
	
		return mapper.writeValueAsString(nameStruct);		
	}
	
	private String checkUserID(String id) throws JsonGenerationException, JsonMappingException, IOException
	{
		UserProfile user = dao.getUserProfileById(id);
		Map<String,String> nameStruct = new HashMap<String,String>();
		
		if(user == null)
			nameStruct.put("result", "pass");
		else
			nameStruct.put("result", "fail");
		return mapper.writeValueAsString(nameStruct);	
	}
	
	private void updateLoc(String id, double x, double y)
	{
		UserProfile user = dao.getUserProfileById(id);
		user.getStatus().setX(x);
		user.getStatus().setY(y);
		dao.ofy().put(user);	
	}
	
	private void updateRange(String id, int range)
	{
		UserProfile user = dao.getUserProfileById(id);
		user.setRange(range);
		dao.ofy().put(user);	
	}
	
	private void createXmppUser(String usr) throws MalformedURLException
	{
		String pwd = usr;
		String secreat = "e7QmAazV";
		URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
		URL url = new URL("http://cad117.cs.nthu.edu.tw:9090/plugins/userService/userservice?type=add&secret="+secreat+
                "&username="+usr+"&password="+pwd);
		try {
	            HTTPResponse response = fetcher.fetch(url);
	            // if response is OK , forward the result to the client
	    }catch(Exception e) {
	           System.out.println(e.getMessage());
	    }
		
	}
	
	private void createUser(HttpServletRequest req)
	{		
		String uid = req.getParameter("id");
		
		//Check if this user is existed?
		UserProfile user = dao.getUserProfileById(uid);
		if(user!=null)
			return;
		
		//Create User
		try {
			String fbid = req.getParameter("fbid");
			UserProfile up = dao.getOrCreateUserProfile(
					uid,
					fbid,
					req.getParameter("name"),
					req.getParameter("gender")
					);
			
			createXmppUser(fbid);
			up.setJid(fbid);					
			dao.ofy().put(up);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String action = req.getParameter("action");
		String uid = req.getParameter("id");
		String fbid = req.getParameter("fbid");
		
		String result = "No Action!!";
		if(action!=null){
			if(action.equals("view")) {	
				result = getUserProfile(uid);
			}
			else if(action.equals("name")) {
				if(fbid==null)
					result = getUserName(uid);
				else
					result = getUserNameByFB(fbid);
			}
			else if(action.equals("check")) {
				result = checkUserID(uid);
			}		
		}
			
		resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
  
		out.println(result);
        out.close();	
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {		

			String action = req.getParameter("action");
			String uid = req.getParameter("id");
			
			if(action.equals("create")) {
				createUser(req);
			}
			else if(action.equals("location")) {
				double x = Double.parseDouble(req.getParameter("x"));
				double y = Double.parseDouble(req.getParameter("y"));
				updateLoc(uid, x, y);
			}
			else if(action.equals("updaterange")) {
				int range = Integer.parseInt(req.getParameter("range"));
				updateRange(uid, range);
			}
	}

}
